#! /usr/bin/python2.7

import os, os.path, sys, time, select, signal

PPS_CONTROLLER = "/pps/services/cellular/radioctrl/control?wait";
PPS_STATUS = "/pps/services/cellular/radioctrl/status_public";
PPS_STATUS_PRIVATE_WAIT = "/pps/services/radioctrl/modem0/status_private?wait,delta";
PPS_STATUS_PERSIST_WAIT = "/pps/services/radioctrl/modem0/status_persistent?wait,delta";

gExit = False;

def radiocontrol(cmd):
	fd = os.open(PPS_CONTROLLER, os.O_RDWR);
	request = "msg::power\n";
	request = request + "id::radioctrlpy\n";
	request = request + ("dat:json:{\"state\":\"" + cmd + "\"}\n");
	print "REQ \n{0}".format( request );
	os.write(fd, request);
	response = os.read(fd, 4 * 1024);
	print "RESP \n{0}".format( response );
	os.close(fd);

def radiostatus_simple():
	fd = os.open(PPS_STATUS, os.O_RDONLY);
	status = os.read(fd, 4 * 1024);
	print "STATUS \n{0}".format( status );
	os.close(fd);

def radiostatus_wait():
	fd_private = os.open(PPS_STATUS_PRIVATE_WAIT, os.O_RDONLY);
	fd_persist = os.open(PPS_STATUS_PERSIST_WAIT, os.O_RDONLY);
	poller = select.poll();
	poller.register(fd_private, select.POLLIN);
	poller.register(fd_persist, select.POLLIN);
	global gExit;
	while not gExit:
		try:
			for fd, event in poller.poll(1000):
				if fd is fd_private:
					print "status_private:\n";
				elif fd is fd_persist:
					print "status_persist:\n";
				else:
					print "unknown fd\n";
					gExit = True;
					break;
			
				status = os.read(fd, 4 * 1024);
				print status;
		except:
			pass;
			
	os.close(fd_private);
	os.close(fd_persist);
	
def radiostatus(wait):
	if wait == True:
		radiostatus_wait();
	else:
		radiostatus_simple();

def on_term(signum, frame):
	print "signal {0} received.\n".format( signum );
	global gExit;
	gExit = True;
		
def main():
	if len(sys.argv) < 2:
		radiostatus(False);
	else:
		signal.signal(signal.SIGTERM, on_term);
		signal.signal(signal.SIGINT, on_term);
		radiocontrol(sys.argv[1].upper());
		radiostatus(True);
		
if __name__ == "__main__":
	main();